﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;

namespace Heyu.Utility
{
    public class HttpRequestUtility
    {
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

        /// <summary>
        /// 发起请求 返回HttpWebResponse
        /// </summary>
        /// <param name="url"></param>
        /// <param name="bodys"></param>
        /// <param name="headers"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static HttpWebResponse GetHttpResponse(string url, string bodys = "", Dictionary<string, string> headers = null, string method = "GET")
        {
            HttpWebRequest httpRequest = null;
            if (url.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;

            if (headers != null)
            {
                foreach (var item in headers)
                {
                    httpRequest.Headers.Add(item.Key, item.Value);
                }
            }

            if (bodys.Length > 0)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }

            HttpWebResponse httpResponse = null;
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            return httpResponse;
        }


        public static string GetStringData(string url, string bodys = "", Dictionary<string, string> headers = null, string method = "GET")
        {
            HttpWebResponse httpResponse = GetHttpResponse(url, bodys, headers, method);
            Stream stream = httpResponse.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
            return reader.ReadToEnd();
        }

        ///// <summary>
        ///// 请求url地址，返回字符串。
        ///// </summary>
        ///// <param name="url"></param>
        ///// <returns></returns>
        //public static string GetStringData(string url)
        //{
        //    byte[] rsByte = GetByteData(url);

        //    return System.Text.Encoding.UTF8.GetString(rsByte, 0, rsByte.Length).ToString();
        //}

        /// <summary>
        /// 请求url地址，返回byte
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static byte[] GetByteData(string url, string bodys = "", Dictionary<string, string> headers = null, string method = "GET")
        {
            HttpWebResponse httpResponse = GetHttpResponse(url, bodys, headers, method);

            Stream stream = httpResponse.GetResponseStream();
            byte[] rsByte = new Byte[httpResponse.ContentLength];

            stream.Read(rsByte, 0, (int)httpResponse.ContentLength);
            return rsByte;
        }
        /// <summary>
        /// 请求URL地址返回xml文档
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static XmlDocument GetXmlData(string url, string bodys = "", Dictionary<string, string> headers = null, string method = "GET")
        {
            XmlDocument xmlDoc = new XmlDocument();

            string data = GetStringData(url, bodys, headers, method);

            xmlDoc.LoadXml(data);

            return xmlDoc;
        }


        /// <summary>
        /// 判断远程文件是否存在1
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public static bool IsExist(string uri)
        {
            HttpWebRequest req = null;
            HttpWebResponse res = null;
            try
            {
                req = (HttpWebRequest)WebRequest.Create(uri);
                req.Method = "HEAD";
                req.Timeout = 100;
                res = (HttpWebResponse)req.GetResponse();
                return (res.StatusCode == HttpStatusCode.OK);
            }
            catch
            {
                return false;
            }
            finally
            {
                if (res != null)
                {
                    res.Close();
                    res = null;
                }
                if (req != null)
                {
                    req.Abort();
                    req = null;
                }
            }
        }

        /// <summary>
        /// 判断远程文件是否存在2
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public static bool UrlExistsUsingXmlHttp(string url)
        {
            //注意：此方法需要引用Msxml2.dll
            //MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass();
            //_xmlhttp.open("HEAD", url, false, null, null);
            //_xmlhttp.send("");
            //return (_xmlhttp.status == 200);

            return false;
        }



        /// <summary>
        /// 判断远程文件是否存在3
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public static bool UrlExistsUsingSockets(string url)
        {
            if (url.StartsWith("http://")) url = url.Remove(0, "http://".Length);
            try
            {
                System.Net.IPHostEntry ipHost = System.Net.Dns.GetHostEntry(url);// System.Net.Dns.Resolve(url);
                return true;
            }
            catch (System.Net.Sockets.SocketException se)
            {
                System.Diagnostics.Trace.Write(se.Message);
                return false;
            }
        }


    }
}
